package com.demo.collector.netty;

import com.demo.collector.netty.server.AirServer;
import com.demo.collector.netty.server.HumiServer;
import com.demo.collector.netty.server.TempServer;
import com.demo.collector.util.properties.ServerPortProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 沈伟峰
 */
@Component
@Slf4j
@EnableConfigurationProperties(ServerPortProperties.class)
public class NettyServerController {

    private final Map<String, NettyServer> servers;

    @Autowired
    NettyServerController(ServerPortProperties portProperties) {
        servers = new HashMap<>();
        try {
            if (portProperties == null)
                throw new Exception("ports load error.");
            servers.put("temp", new TempServer(portProperties.getPort("temp")));
            servers.put("humi", new HumiServer(portProperties.getPort("humi")));
            servers.put("air", new AirServer(portProperties.getPort("air")));
        } catch (Exception e) {
            log.error(e.toString());
        }
    }

    private NettyServer getServer(String name) throws Exception {
        if (!servers.containsKey(name))
            throw new Exception("server not found.");
        return servers.get(name);
    }

    public void start(String name) throws Exception {
        getServer(name).start();
    }

    public void close(String name) throws Exception {
        getServer(name).close();
    }

    @PostConstruct
    public void startAll() {
        for (NettyServer server : servers.values()) {
            try {
                server.start();
            } catch (Exception e) {
                log.error(e.toString());
            }
        }
    }

    @PreDestroy
    public void closeAll() {
        for (NettyServer server : servers.values()) {
            try {
                server.close();
            } catch (Exception e) {
                log.error(e.toString());
            }
        }
    }

}
